<!DOCTYPE html>
<title>Tests that the closed captions button enables track switching.</title>
<script src='../../resources/testharness.js'></script>
<script src='../../resources/testharnessreport.js'></script>
<script src='../media-controls.js'></script>
<video controls>
  <track src='../track/captions-webvtt/captions-fast.vtt' kind='captions'>
  <track src='../track/captions-webvtt/captions-rtl.vtt' kind='captions'>
</video>
<script>
async_test(t => {
  var video = document.querySelector('video');
  enableTestMode(video);

  video.onplaying = t.step_func(_ => {
    video.onplaying = null;
    assert_true(isClosedCaptionsButtonEnabled(video));

    // The captions track should be listed in textTracks, but not yet loaded.
    assert_equals(video.textTracks.length, 2);
    assert_equals(video.textTracks[0].mode, 'disabled');
    assert_equals(video.textTracks[1].mode, 'disabled');
    assert_equals(textTrackContainerElement(video), null);

    var tracks = document.querySelectorAll('track');
    tracks[0].onload = t.step_func(_ => {
      // Resume video
      video.play();

      assert_equals(textTrackDisplayElement(video).innerText, 'Lorem');

      // Captions should not be visible after Off is clicked.
      turnClosedCaptionsOff(video, t.step_func(() => {
        assert_equals(textTrackDisplayElement(video), null);

        // Remove the track elements.
        tracks[1].remove();
        tracks[0].remove();

        // The controls are updated asynchronously.
        setTimeout(t.step_func(_ => {
          assert_false(isClosedCaptionsButtonEnabled(video));

          // Add non-default text track through HTML with unloadable URI.
          var track = document.createElement('track');
          track.setAttribute('src', 'invalid.vtt');

          track.onerror = t.step_func(_ => {
            // Track failed to load.
            assert_false(isClosedCaptionsButtonVisible(video));
            // Add a text track through JS to the video element.
            var newTrack = video.addTextTrack('captions', 'English', 'en');
            setTimeout(t.step_func_done(_ => {
              assert_true(isClosedCaptionsButtonEnabled(video));
            }));
          });

          video.appendChild(track);
          assert_equals(track.readyState, HTMLTrackElement.NONE);
          assert_equals(track.track.mode, 'disabled');
          assert_equals(video.textTracks.length, 1);

          setTimeout(t.step_func(_ => {
            assert_true(isClosedCaptionsButtonEnabled(video));
            clickTextTrackAtIndex(video, 0);
          }));
        }));
      }));

    });

    // Captions track should load and captions should become visible after a track is selected.
    clickTextTrackAtIndex(video, 0);

    // Pause the video until track is loaded
    video.pause();
  });

  video.src = '../content/counting.ogv';
  video.play();
});
</script>

